package com.jeesite.modules.api.service;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson2.function.impl.ToDouble;
import com.jeesite.common.service.CrudService;
import com.jeesite.modules.api.dao.BaseInfoDao;
import com.jeesite.modules.information.dao.BasicInformationDao;
import com.jeesite.modules.information.entity.BasicInformation;
import com.jeesite.modules.information.entity.DailySigns;
import com.jeesite.modules.information.entity.KyAdvice;
import com.jeesite.modules.information.entity.PlatformIdMapping;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDate;
import java.util.List;
import java.util.UUID;

/**
 * @author weidong
 * @description: TODO
 * @date 2024年07月01日
 */
@Slf4j
@Service
public class BaseInfoService  extends CrudService<BasicInformationDao, BasicInformation> {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private BaseInfoDao baseInfoDao;
    // 订单状态常量，提高可读性和可维护性
    private static final int ORDER_STATE_UNPAID = 1;    // 未支付
    private static final int ORDER_STATE_COMPLETED = 4; // 已完成

    public BasicInformation getBaseInfo(String phone) {
        return baseInfoDao.getBaseInfo(phone);
    }

    public List<JSONObject> listAppointment(String phone, String startTime) {
        return baseInfoDao.listAppointment(phone, startTime);
    }

    public JSONObject getNowInfo(String phone, String startTime) {
        JSONObject jsonObject = new JSONObject();
        // 最后一条日常体征数据
        JSONObject daily = baseInfoDao.getLastDaily(phone);
        jsonObject.put("daily",daily);
        // 科室排行统计
        List<JSONObject> departments = baseInfoDao.getDepartmentRanking(phone,startTime);
        jsonObject.put("departments",departments);
        return jsonObject;
    }

    public List<JSONObject> listAdvice(String phone, String adate) {
        return baseInfoDao.listAdvice(phone,adate);
    }

    public List<JSONObject> listTemprature(String phone) {
        return baseInfoDao.listTemprature(phone);
    }

    public List<JSONObject> listHeartRate(String phone) {
        return baseInfoDao.listHeartRate(phone);
    }

    public List<JSONObject> listBloodPressure(String phone) {
        return baseInfoDao.listBloodPressure(phone);
    }

    public PlatformIdMapping getMappingId(String phone) {
        BasicInformation baseInfo = baseInfoDao.getBaseInfo(phone);
        if (baseInfo != null) {
            return baseInfoDao.getPlatformIdMapping(baseInfo.getId());
        }
        return null;
    }


    public void InsertAorder(String phone) {
        BasicInformation baseInfo = baseInfoDao.getBaseInfo(phone);
        PlatformIdMapping platformIdMapping = baseInfoDao.getPlatformIdMapping(baseInfo.getId());
        String platformAId = platformIdMapping.getPlatformAId();
        String platformBId = platformIdMapping.getPlatformBId();
        String platformCId = platformIdMapping.getPlatformCId();
        List<JSONObject> jsonObjects = null;
        if(platformAId!=null ) {
            jsonObjects = baseInfoDao.getlistAppointmentByPhone(phone);
            jsonObjects.stream().forEach(jsonObject -> {
                jsonObject.put("buy_user_id",platformAId);
            });

        }
        // TODO 调用A平台接口，插入预约订单
        OrderResponse response = callOrderProcessingApi(jsonObjects,"xxx");
         if (response == null || response.getData() == null) {
             return;
         }
        List<Boolean> processResults = response.getData().getList();
        updateOrderStates(jsonObjects, processResults);




    }
    public void InsertBorder(String phone) {
        BasicInformation baseInfo = baseInfoDao.getBaseInfo(phone);
        PlatformIdMapping platformIdMapping = baseInfoDao.getPlatformIdMapping(baseInfo.getId());

        String platformBId = platformIdMapping.getPlatformBId();

        List<JSONObject> jsonObjects = null;
        if(platformBId!=null ) {
            jsonObjects = baseInfoDao.getlistAppointmentByPhone(phone);
            jsonObjects.stream().forEach(jsonObject -> {
                jsonObject.put("buy_user_id",platformBId);
            });

        }
        // TODO 调用A平台接口，插入预约订单
        OrderResponse response = callOrderProcessingApi(jsonObjects,"xxx");
        if (response == null || response.getData() == null) {
            return;
        }
        List<Boolean> processResults = response.getData().getList();
        updateOrderStates(jsonObjects, processResults);




    }
    public void InsertCorder(String phone) {
        BasicInformation baseInfo = baseInfoDao.getBaseInfo(phone);
        PlatformIdMapping platformIdMapping = baseInfoDao.getPlatformIdMapping(baseInfo.getId());

        String platformCId = platformIdMapping.getPlatformCId();
        List<JSONObject> jsonObjects = null;
        if(platformCId!=null ) {
            jsonObjects = baseInfoDao.getlistAppointmentByPhone(phone);
            jsonObjects.stream().forEach(jsonObject -> {
                jsonObject.put("buy_user_id",platformCId);
            });

        }
        // TODO 调用A平台接口，插入预约订单
        OrderResponse response = callOrderProcessingApi(jsonObjects,"xxxx");
        if (response == null || response.getData() == null) {
            return;
        }
        List<Boolean> processResults = response.getData().getList();
        updateOrderStates(jsonObjects, processResults);




    }


    @Data
    public static class OrderResponse {  // 改为静态内部类，避免序列化问题
        private String status;
        private OrderData data;
    }

    /**
     * 响应数据实体类
     */
    @Data
    public static class OrderData {
        private List<Boolean> list;
    }

    /**
     * 调用外部接口获取订单处理结果
     */
    private OrderResponse callOrderProcessingApi(List<JSONObject> orderList,String url) {
        try {
            return restTemplate.postForObject(url, orderList, OrderResponse.class);
        } catch (RestClientException e) {
            log.error("调用订单接口失败，URL: {}", e);
            return null;
        }
    }
    private void updateOrderStates(List<JSONObject> orderList, List<Boolean> processResults)
             {

        // 校验列表大小
        if (orderList.size() != processResults.size()) {
            throw new IllegalArgumentException(
                    String.format("订单列表与结果列表大小不匹配: 订单数=%d, 结果数=%d",
                            orderList.size(), processResults.size()));
        }

        // 遍历处理订单状态更新
        for (int i = 0; i < orderList.size(); i++) {
            JSONObject order = orderList.get(i);
            Boolean shouldComplete = processResults.get(i);
            if (shouldComplete != null && shouldComplete) {
                order.put("state", ORDER_STATE_COMPLETED);
                baseInfoDao.updateOrder(order);
            }
        }


    }


    public void updateBasicInformation(BasicInformation basicInformation) {
        baseInfoDao.updateBasicInformation(basicInformation);
        String id = basicInformation.getId();
        PlatformIdMapping mappingId = getMappingId(id);
        if (mappingId != null) {
            mappingId.setPlatformAId(basicInformation.getIdentificationNumber());
            mappingId.setPlatformDId(basicInformation.getIdentificationNumber());
            baseInfoDao.updatePlatformIdMapping(mappingId);
        } else {
            mappingId = new PlatformIdMapping();
            mappingId.setPlatformId(id);
            mappingId.setPlatformAId(basicInformation.getIdentificationNumber());
            mappingId.setPlatformBId(basicInformation.getPatientPhone());
            mappingId.setPlatformCId(basicInformation.getPatientPhone());
            mappingId.setPlatformDId(basicInformation.getIdentificationNumber());
            baseInfoDao.insertPlatformIdMapping(mappingId);
        }

    }

    public void labelUpdate(BasicInformation basicInformation){
        baseInfoDao.labelUpdate(basicInformation);
    }

    public void insertAdvices(List<KyAdvice> kyAdvices){
        for(KyAdvice kyAdvice:kyAdvices) {
            LocalDate currentDate = LocalDate.now();
            kyAdvice.setId(UUID.randomUUID().toString().replaceAll("-", "").substring(0, 20));
            kyAdvice.setRiqi(currentDate);
            kyAdvice.setCreateDate(currentDate);
            kyAdvice.setUpdateDate(currentDate);
            kyAdvice.setCreateBy("system");
            kyAdvice.setUpdateBy("system");
            baseInfoDao.insertAdvice(kyAdvice);
        }
    }
}
